<template>
  <div class="SchoolLoginBox">
    <div class="SchoolLoginCenterBox">
      <div class="centerLeft">
      </div>
      <div class="centerRight">
        <div class="rightContent" v-on:keyup.enter="submitLogin">
          <Card>
            <div class="top">
              <p>河南省高校毕业生</p>
              <p>毕业去向登记平台</p>
            </div>
            <Form ref="schoolLoginForm" :model="formSchool" :rules="rulesSchool" class="loginFormBox">
              <FormItem prop="username">
                <Input v-model="formSchool.username" size="large" clearable placeholder="请输入账号"
                       autocomplete="off">
                  <template #prefix>
                    <img src="@/assets/username.png" style="width: 22px; height: 22px" />
                  </template>
                </Input>
              </FormItem>
              <FormItem prop="password">
                <Input type="password" v-model="formSchool.password" size="large" password
                       placeholder="请输入密码"
                       autocomplete="off">
                  <template #prefix>
                    <img src="@/assets/password.png" style="width: 22px; height: 22px" />
                  </template>
                </Input>
              </FormItem>
              <FormItem v-if="showCode" prop="code">
                <div style="display: flex; justify-content: space-between; width: 100%">
                  <Input v-model="formSchool.code" size="large" clearable placeholder="请输入短信验证码"
                         :maxlength="10" class="input-verify" style="float: left">
                    <template #prefix>
                      <img src="@/assets/yzm.png" style="width: 22px; height: 22px" />
                    </template>
                  </Input>
                  <CountDownButton ref="countDown" @on-click="showVaptcha1" :autoCountDown="false" size="large"
                                   :loading="sending" :text="getSms" />
                  <Captcha v-if="showCaptcha1" @onSuccess="okSend" ref="captcha"></Captcha>

                </div>
              </FormItem>

              <FormItem>
                <Button :loading="loading" @click.native="submitLogin" long>登录</Button>
                <div class="last">
                </div>
              </FormItem>
              <Alert type="info" show-icon>如账号登录有问题，请联系上级就业管理部门。</Alert>
            </Form>
          </Card>
        </div>
      </div>
    </div>
    <Modal v-model="showModal" title="信息补充">
      <Form ref="schoolLoginFormModal" :model="formSchoolModal" :rules="rulesSchoolModal" class="loginFormBox"
            :label-width="180">
        <FormItem prop="password" label="原始密码">
          <Input type="password" v-model="formSchoolModal.password" size="large" password
                 placeholder="请输入密码"
                 autocomplete="off">
            <template #prefix>
              <img src="@/assets/password.png" style="width: 22px; height: 22px" />
            </template>
          </Input>
        </FormItem>
        <FormItem label="新密码" prop="newPass"
                  :rules="[{ required: true, trigger: 'blur', validator: validatePassword1 }]">
          <Input type="password" password v-model="formSchoolModal.newPass" @on-change="ModalchangeInputPass"
                 placeholder="请输入新密码">
            <template #prefix>
              <img src="@/assets/password.png" style="width: 22px; height: 22px" />
            </template>
          </Input>
        </FormItem>
        <FormItem label="确认密码" prop="copypwd"
                  :rules="[{ required: true, trigger: 'blur', validator: validatePassword2 }]">
          <Input type="password" password v-model="formSchoolModal.copypwd" placeholder="请再次输入新密码">
            <template #prefix>
              <img src="@/assets/password.png" style="width: 22px; height: 22px" />
            </template>
          </Input>
        </FormItem>
        <FormItem label="手机号" prop="mobile" :error="errorMobile">
          <Input v-model="formSchoolModal.mobile" size="large" clearable placeholder="请输入手机号"
                 autocomplete="off">
            <template #prefix>
              <Icon type="md-phone-portrait" style="color: rgb(136, 199, 250)" />
            </template>
          </Input>
        </FormItem>
        <FormItem label="部门名称" prop="sectionName">
          <Input v-model="formSchoolModal.sectionName" size="large" clearable placeholder="请输入部门名称"
                 autocomplete="off">
            <template #prefix>
              <Icon type="md-analytics" style="color: rgb(136, 199, 250)" />
            </template>
          </Input>
        </FormItem>
        <FormItem label="部门负责人" prop="sectionPerson">
          <Input v-model="formSchoolModal.sectionPerson" size="large" clearable
                 placeholder="请输入部门负责人姓名"
                 autocomplete="off">
            <template #prefix>
              <Icon type="md-contact" style="color: rgb(136, 199, 250)" />
            </template>
          </Input>
        </FormItem>
        <FormItem label="部门负责人手机号" prop="sectionMobile" :error="errorMobile">
          <Input v-model="formSchoolModal.sectionMobile" size="large" clearable
                 placeholder="请输入部门负责人手机号"
                 autocomplete="off">
            <template #prefix>
              <Icon type="md-phone-portrait" style="color: rgb(136, 199, 250)" />
            </template>
          </Input>
        </FormItem>
        <Row>
          <FormItem prop="code">
            <div style="display: flex; justify-content: space-between; width: 100%">
              <Input v-model="formSchoolModal.code" size="large" clearable placeholder="请输入短信验证码"
                     :maxlength="10" class="input-verify" style="float: left">
                <template #prefix>
                  <img src="@/assets/yzm.png" style="width: 22px; height: 22px" />
                </template>
              </Input>
              <CountDownButton ref="countDown" @on-click="showVaptcha" :autoCountDown="false" size="large"
                               :loading="sending" :text="getSms" />
              <!--                            <slidingVerification ref="slidingv" @onOk="onOkModal" :modalShow="true" />-->
              <Captcha v-if="showCaptcha" @onSuccess="onOkModal" ref="captcha"></Captcha>

            </div>
          </FormItem>
        </Row>
      </Form>
      <div style="display: flex; justify-content: center">
        <Button :loading="loading" @click.native="submitModal" type="primary" style="width: 30%">提交</Button>
      </div>
      <div></div>
      <div slot="close"></div>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>
<script>
import {
  login,
  userInfoToken,
  modifyPassFirstLogin,
  sendUpdatePassCode, sendLoginSms, sendLoginByUsernameSms
} from '@/api';
import util from '@/libs/util';
import SetPassword from '@/views/my-components/xboot/set-password.vue';
import CountDownButton from '@/views/my-components/xboot/count-down-button.vue';
import slidingVerification from '@/views/my-components/xboot/sliding-verification.vue';
import { validateMobile } from '@/libs/validate';
import CryptoJS from 'crypto-js';
import Captcha from '@/components/captcha.vue';
import { getFixedSelect } from '@/api/qyManage';

export default {
  components: { slidingVerification, CountDownButton, SetPassword, Captcha },
  data() {
    return {
      showCaptcha: false,
      showCaptcha1: false,
      loading: false,

      formSchool: {
        username: '',
        password: '',
        resource: '2',
        code: ''
      },

      rulesSchool: {
        username: [
          {
            required: true,
            message: '账号不能为空',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
          }
        ]
      },
      // 弹框
      formSchoolModal: {
        password: '',
        newPass: '',
        mobile: '',
        code: '',
        copypwd: '',
        passStrength: '',
        sectionMobile: '',
        sectionName: '',
        sectionPerson: ''
      },
      rulesSchoolModal: {
        password: [
          {
            required: true,
            message: '请输入原密码',
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            validator: validateMobile,
            trigger: 'change'
          }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空',
            trigger: 'blur'
          }
        ]
      },
      showModal: false,
      showCode: false,
      // 错误提示
      errorMobile: '',
      resource: '2',
      getSms: '获取验证码',
      sending: false
    };
  },
  created() {
    this.getSelect()
  },
  methods: {
    // 清空缓存

    //登录提交
    submitLogin() {
      this.$refs.schoolLoginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.formSchool.resource = this.resource;
          // 将密钥转换为WordArray对象
          const keyWordArray = CryptoJS.enc.Utf8.parse('d77f1e8084e21d96');
          // 加密
          const encrypted = CryptoJS.AES.encrypt(this.formSchool.password, keyWordArray, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
          });
          let form = { ...this.formSchool };
          form.password = encrypted.toString();
          login(form).then(res => {
            if (res.success) {
              this.loading = false;
              this.afterLogin(res);
            } else {
              this.loading = false;
            }
          });
        }
        this.loading = false;
      });
    },

    getSelect() {
      getFixedSelect().then(res => {
        if (res.success) {
          this.showCode = res.result.loginValidateSwitch;
        }
      })
    },
    afterLogin(res) {
      console.log('登录返回', res);
      let accessToken = res.result;
      this.token = accessToken;
      // 获取用户信息
      userInfoToken(accessToken).then(res => {
        console.log('用户信息', res);
        if (!['2', '3'].includes(this.resource)) {
          this.$Message.error({
            content: '登录入口错误！',
            duration: 5,
            closable: true
          });
        } else {
          if (res.success) {
            if (res.result.firstLogin && (this.resource == '2' || this.resource == '3')) {
              this.showModal = true;
              // 回填 部门名称 部门负责人 部门负责人手机号
              this.formSchoolModal.sectionName = res.result.sectionName ?? '';
              this.formSchoolModal.sectionPerson = res.result.sectionPersonName ?? '';
              this.formSchoolModal.sectionMobile = res.result.sectionPersonMobile ?? '';

              this.loading = false;
            } else {
              console.log('false');
              // window.location.reload();
              // 避免超过大小限制
              this.setStore('accessToken', accessToken);
              delete res.result.permissions;
              let roles = [];
              res.result.roles.forEach(e => {
                roles.push(e.name);
              });
              delete res.result.roles;
              this.setStore('roles', roles);
              this.setStore('saveLogin', this.saveLogin);
              if (this.saveLogin) {
                // 保存7天
                Cookies.set('userInfo', JSON.stringify(res.result), {
                  expires: 7
                });
                Cookies.set('currentUser', this.$route.name, {
                  expires: 7
                });
              } else {
                Cookies.set('userInfo', JSON.stringify(res.result));
                Cookies.set('currentUser', this.$route.name);
              }
              this.$store.commit('setRoute', this.$route.name);
              this.setStore('userInfo', res.result);
              this.$store.commit('setUserInfo', res.result);
              // 加载菜单
              util.initRouter(this);
              // window.location.reload()
              console.log(this.saveLogin, 'coll');
              if (roles[0] === 'ROLE_PROVINCE_MARKET' || roles[0] === 'ROLE_MARKET') {
                this.$router.push({
                  path: '/jobAudit'
                });
              } else {
                this.$router.push({
                  path: '/home'
                });
              }

            }
          }
        }
      });
    },
    onOkModal() {
      this.showCaptcha = false;
      this.sending = true;
      let obj = {
        mobile: this.formSchoolModal.mobile
      };
      console.log(obj, '---obj');
      this.loading = true;
      sendUpdatePassCode(this.token, obj).then(res => {
        this.loading = false;
        console.log(res, '-----------------res');
        if (res.success) {
          this.getSms = '发送中';
          this.$Message.success('发送短信验证码成功');
          // 开始倒计时
          this.$nextTick(() => {
            this.$refs.countDown.startCountDown();
          });
        }
        this.sending = false;
      });
    },
    okSend() {
      this.showCaptcha1 = false;
      this.sending = true;
      this.loading = true;
      sendLoginByUsernameSms({
        username: this.formSchool.username
      }).then(res => {
        this.loading = false;
        if (res.success) {
          this.getSms = '重新发送';
          this.$Message.success('发送短信验证码成功');
          // 开始倒计时
          this.$nextTick(() => {
            this.$refs.countDown.startCountDown();
          });
        }
        this.sending = false;
      });
    },
    // 弹框提交
    submitModal() {
      let {
        newPass,
        copypwd,
        mobile,
        code,
        passStrength,
        password,
        sectionMobile,
        sectionPerson,
        sectionName
      } = this.formSchoolModal;
      console.log(copypwd, '--------');
      this.$refs.schoolLoginFormModal.validate(valid => {
        if (valid) {
          if (newPass === copypwd) {
            this.loading = true;
            // 请求接口
            modifyPassFirstLogin(this.token, {
              password: password,
              newPass: newPass,
              passStrength: passStrength,
              mobile: mobile,
              code: code,
              sectionName: sectionName,
              sectionPerson: sectionPerson,
              sectionMobile: sectionMobile,
              username: this.formSchool.username
            }).then(res => {
              if (res.success) {
                console.log(res);
                this.showModal = false;
                this.loading = false;
              } else {
                this.loading = false;
              }
            });
          } else {
            this.$Message.error({
              content: '两次密码不一致！',
              duration: 5,
              closable: true
            });
          }
        }
      });
    },
    //密码强度
    ModalchangeInputPass(v, grade, strength) {
      this.formSchoolModal.passStrength = strength;
    },
    showVaptcha() {
      this.$refs.schoolLoginForm.validate(valid => {
        if (valid) {
          let { newPass, copypwd } = this.formSchoolModal;
          if (newPass === copypwd) {
            var reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
            if (!reg.test(this.formSchoolModal.mobile)) {
              this.errorMobile = '手机号格式错误';
              return;
            } else {
              this.errorMobile = '';
              this.sendSmsCode();
            }
          } else {
            // this.$Message.error('两次密码不一致！');
            this.$Message.error({
              content: '两次密码不一致！',
              duration: 5,
              closable: true
            });
          }
        }
      });
    },
    showVaptcha1() {
      this.showCaptcha1 = true;
    },
    sendSmsCode() {
      this.showCaptcha = true;
    }
  }
};
</script>

<style scoped lang="less">
@import './schoolLogin.less';
</style>
